//
//  AudioObject.m
//  MooreDoll
//
//  Created by Orange on 2014/12/29.
//  Copyright (c) 2014年 Tank. All rights reserved.
//
#define AVAudioSessionShare    [AVAudioSession sharedInstance]
#define NotificationDefault  [NSNotificationCenter defaultCenter]

#import "AudioObject.h"
#import <AVFoundation/AVFoundation.h>

@interface AudioObject()<AVAudioRecorderDelegate,AVAudioPlayerDelegate>
@property (strong, nonatomic) AVAudioRecorder   *audioRecord;
@property (strong, nonatomic) AVAudioPlayer     *audioPlayer;
@property (strong, nonatomic) NSString          *fileRecord;
@property (strong, nonatomic) NSTimer           *timer;
@property int timeInt;
@end
@implementation AudioObject


#pragma mark - Recorder
+ (id)sharedManager {
    static AudioObject *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}
- (void)dealloc {

}
- (void) audioObjectDrawRect {

    [self recordActive];
    _timeInt = 0;
}

- (void)audioObjectAgainRecrderCompletionHandler: (void (^)(BOOL))completionHandler  {
    _timeInt = 0;
    completionHandler( _audioRecord.recording);
}
- (void)audioObjectSaveRecorderCompletionHandler:(void (^)(NSString *))completionHandler {
    [self timeNil];
    [_audioPlayer stop];
    _audioRecord = nil;
    
    [AVAudioSessionShare setActive: NO error: nil];
    
    completionHandler(_fileRecord);
}
- (void)audioObjectAudioStartCompletionHandler: (void (^)(BOOL))completionHandler {
    [self timeInterval: @selector(TimerCallback:)];
    [self recordPrepareToRecord];
    completionHandler( _audioRecord.recording);
}
- (void) audioObjectAudioPlayCompletionHandler: (void (^)(BOOL))completionHandler {
    [_audioRecord stop];
    [self timeNil];
    [self playerActive: _fileRecord];

    completionHandler( _audioPlayer.playing);
}
- (void)audioObjectAudioPauseCompletionHandler: (void (^)(BOOL))completionHandler {
    [self playerPrepareToPlay];
    completionHandler( _audioPlayer.playing);
}
- (void)audioObjectAudioStopCompletionHandler: (void (^)(BOOL))completionHandler {
    [self timeNil];
    [_audioPlayer stop];
    completionHandler( _audioPlayer.playing);
}
- (void)audioObjectTimeStop {
    [self timeNil];
    [_audioRecord stop];
    [_audioPlayer stop];
    [AVAudioSessionShare setActive: NO error: nil];
}
#pragma mark - Recorder
- (void) recordActive {
    [AVAudioSessionShare setActive: YES error: nil];
    [AVAudioSessionShare setCategory: AVAudioSessionCategoryPlayAndRecord error: nil];
    
    NSArray         *paths      = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString        *filename   = [[paths objectAtIndex: 0] stringByAppendingPathComponent: @"record.caf"];
    NSURL           *url        = [NSURL fileURLWithPath: filename];
    NSDictionary    *set        = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [NSNumber numberWithFloat: 4100.0],
                                   AVSampleRateKey,
                                   [NSNumber numberWithInt: kAudioFormatAppleLossless],
                                   AVFormatIDKey,
                                   [NSNumber numberWithInt: AVAudioQualityHigh],
                                   AVEncoderAudioQualityKey,
                                   nil];
    
    AVAudioRecorder *recorder   = [[AVAudioRecorder alloc] initWithURL: url settings: set error:nil];
    _fileRecord  = filename;
    _audioRecord = recorder;
}
- (void) recordPrepareToRecord {
    [_audioRecord prepareToRecord];
    [_audioRecord setDelegate: self];
    [_audioRecord record];
}
#pragma mark - Player
- (void) playerActive:(NSString *) path  {
    NSURL           *url        = [NSURL URLWithString: path];
    AVAudioPlayer   *player     = [[AVAudioPlayer alloc] initWithContentsOfURL: url  error: nil];
    _audioPlayer = player;
}
- (void) playerPrepareToPlay {
    _timeInt = 0;
    [self timeInterval: @selector(PlayerTimerCallback:)];
    
    [_audioPlayer setDelegate: self];
    [_audioPlayer prepareToPlay];
    [_audioPlayer setVolume: 10.0];
    [_audioPlayer play];

    NSLog(@"Duration : %f",[_audioPlayer duration]);
}
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    if (flag == YES) {
        NSLog(@"播放完畢");
        [self timeNil];
        if (_delegate && [_delegate respondsToSelector: @selector( audioObjectPlayFinish)]) {
            [_delegate audioObjectPlayFinish];
        }
    }
}
#pragma mark - Time
- (void) timeInterval:(SEL) selector {
    _timer = [NSTimer scheduledTimerWithTimeInterval: 1.0
                                              target: self
                                            selector: selector
                                            userInfo: nil
                                             repeats: YES];
}
- (void) timeNil {
    [_timer invalidate];
    _timer = nil;
}
- (void) PlayerTimerCallback: (id) sender {
    _timeInt++;
    if ([_audioPlayer duration] < _timeInt) {
        return;
    }
    [self timerCallbackDelegate];

}
- (void) TimerCallback: (id) sender {
    _timeInt++;
    [self timerCallbackDelegate];
}
- (void) timerCallbackDelegate {
    if (_delegate && [_delegate respondsToSelector: @selector(audioObjectTimeText:)]) {
        [_delegate audioObjectTimeText: [self timeFormatted: _timeInt]];
    }
}
- (NSString *)timeFormatted:(int)totalSeconds
{
    
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours   = totalSeconds / 3600;
    
    if (hours == 0)
        return [NSString stringWithFormat:@"%02d : %02d", minutes, seconds];
    else
        return [NSString stringWithFormat:@"%02d : %02d : %02d",hours, minutes, seconds];
    
}
@end
